<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models\DataTableModel;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Folder
 * 
 * @property int $folder_id
 * @property string $folder_name
 * @property int $id
 * @property int|null $storage_space
 * @property int|null $parent_folder_id
 * @property string $folder_state
 * @property int $foder_image_id
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * 
 * @property User $user
 * @property Folder|null $folder
 * @property Collection|Folder[] $folders
 *
 * @package App\Models\DataTableModel
 */
class Folder extends Model
{
	protected $table = 'folders';
	protected $primaryKey = 'folder_id';

	protected $casts = [
		'id' => 'int',
		'storage_space' => 'int',
		'parent_folder_id' => 'int',
		'foder_image_id' => 'int'
	];

	protected $fillable = [
		'folder_name',
		'id',
		'storage_space',
		'parent_folder_id',
		'folder_state',
		'foder_image_id'
	];

	public function user()
	{
		return $this->belongsTo(User::class, 'id');
	}

	public function parent()
	{
		return $this->belongsTo(Folder::class, 'parent_folder_id');
	}

	public function folders()
	{
		return $this->hasMany(Folder::class, 'parent_folder_id');
	}
	// 与图标表的联合查询
	public function folder_icon()
	{
		return $this->belongsTo(Icon::class, 'foder_image_id', 'id');
	}
	// 返回文件的根路径
	public function getPath()
	{
		$path = [$this->folder_name];
		$folder = $this;

		while ($folder->parent_folder_id) {
			$folder = $folder->parent;
			array_unshift($path, $folder->folder_name);
		}

		return implode('/', $path);
	}

	public static function getRootFolderNameForUser($userId)
	{
		// 查找 parent_folder_id 为 null 且 id 匹配用户ID的文件夹  
		$rootFolder = self::where('parent_folder_id', null)
			->where('id', $userId) // 假设用户ID直接存储在folder的id字段中，这通常不是最佳实践  
			->first();

		// 如果找到了根目录文件夹，返回其名称；否则返回null或适当的错误消息  
		return $rootFolder ? $rootFolder->folder_name : null;
	}
}
